/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package IDSNN_1_Business;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import javax.swing.JTextArea;

/**
 *
 * @author francisco
 */
public class TcpDump extends Thread
 {
    private JTextArea _trafficTextBox;
    private String path;
    private String user;
    private String pass;
    private String url;
    private String tsPath;
    private IDSNN_1_Data.DBConnect db;
    public TcpDump()
    {
    }

    /*public TcpDump(JTextArea _trafficTextBox, String path,String tsPath) {
        this._trafficTextBox=_trafficTextBox;
        this.path= path;
        this.tsPath = tsPath;
        db = new IDSNN_1_Data.DBConnect(this.pass, this.user, this.url, this.tsPath);
    }*/

    public TcpDump(JTextArea _trafficTextBox, String path,String user, String pass, String tsPath, String url) {
        this._trafficTextBox=_trafficTextBox;
        this.path= path;
        this.user = user;
        this.pass=pass;
        this.url = url;
        this.tsPath = tsPath;
        System.out.println(pass+" - "+user+" - "+url+" - "+tsPath);
        db = new IDSNN_1_Data.DBConnect(pass, user, url, tsPath);
    }


public void main() {
    Thread thread;
    System.out.println("main \n"+this.pass+" - "+this.user+" - "+this.url+" - "+this.tsPath+"\n end main");
    thread = new TcpDump(this._trafficTextBox, this.path, this.user, this.pass, this.tsPath, this.url);
    thread.start();
    
}
public void run() {
    readTcpDump();
}

public void setUser(String user){
    this.user=user;
}

public void setPass(String pass){
    this.pass=pass;
}

public void setURL(String url){
    this.url = url;
}

public void readTcpDump()
    {
    try
    {
        String comando ="";
        /*String command;
        Process child;
        //command = "tcpdump -r /Users/francisco/Documents/Universidade/Mestrado/2Ano/TeseMestrado/Dataset/firstOutside.tcpdump";
        command = "sudo tcpdump -i en1 'tcp[13] & 4!=0 || tcp [13] & 1!=0 || tcp[13] & 2!=0 || tcp[13] =18 || icmp[icmptype]==icmp-echo'";
        //command = "sudo tcpdump -i en1";
        child = Runtime.getRuntime().exec(command);
        InputStream in = child.getInputStream();
        ArrayList<String> arrayString = new ArrayList<String>();
        String comando ="";
        int c;
        char h=' ';
        int contador=0;
        int count =0;
        int i=0;
        while (i<1000000)
        {
            c=in.read();
            h=(char) c;
            if(c==10 && c==13)
            {
                System.out.println("Estou aqui2");
             if(comando.contains("Flags") || comando.contains("ICMP"))
                   {
                         routineExecute(comando);
                         contador++;
                         System.out.println(comando);
                         comando = "";
                         i++;
                   }
             
            }
            
        }
    in.close();
        
        String cmd = "tcpdump -i en1 'tcp[13] & 4!=0 || tcp [13] & 1!=0 || tcp[13] & 2!=0 || tcp[13] =18 || icmp[icmptype]==icmp-echo'";
	Runtime run = Runtime.getRuntime();
	Process pr = run.exec(cmd);
	BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
	String line = "...";
        while(!line.equals("exit")){
            while (line==null || line == "...") {	
                    line=buf.readLine();
                    }
        System.out.println(line);
        }*/
           // run the Unix "ps -ef" command
            // using the Runtime exec method:
            //Process p = Runtime.getRuntime().exec("tcpdump -i en1 tcp[13] & 4!=0 || tcp [13] & 1!=0 || tcp[13] & 2!=0 || tcp[13] =18 || icmp[icmptype]==icmp-echo");
            Process p = Runtime.getRuntime().exec(path);
            
            BufferedReader stdInput = new BufferedReader(new 
                 InputStreamReader(p.getInputStream()));
            BufferedReader stdError = new BufferedReader(new 
                 InputStreamReader(p.getErrorStream()));
            System.out.println("Starting capture\n");
            while ((comando = stdInput.readLine()) != null) {
                routineExecute(comando);
                _trafficTextBox.append(comando+"\n");
                //System.out.println(comando);
            }
            System.out.println("Error\n");
            while ((comando = stdError.readLine()) != null) {
                System.out.println(comando);
            }
            
    }
    catch (Exception e)
    {
            e.printStackTrace();
    }
    finally
    {
        this.readTcpDump();
    }
}

private void routineExecute(String aux)
    {
    if(aux.contains("ICMP") && aux.contains("request"))
        routineICMP(aux);
    else
        routineFlags(aux);
    }


private void routineICMP(String aux)
    {
        String[] part = aux.split(" ");
        
        int cod=-1;
        int codF=-1;
        int tam= part[4].length();
        part[4]=part[4].substring(0, tam-1);
        cod=db.checkExistingMain(part[2], part[4]);
        if(cod!=-1)
        {
            codF=db.checkExistingFlags(cod);
            if(codF!=-1)
                db.updateFlag(cod, 0, 0, 0, 0, 1);
            else
                db.addFlag(cod, 0, 0, 0, 0, 1);
        }
        else{
            db.addMainTable(part[2], part[4]);
            cod=db.checkExistingMain(part[2], part[4]);
            db.addFlag(cod, 0, 0, 0, 0, 1);
        }
    }


private void routineFlags(String aux)
    {
        try{
        String[] part = aux.split(" ");
        String window = "";
        String[] part2 = aux.split(",");
        for(String auxPart : part2){
            if(auxPart.contains("win")){
                window = auxPart.split(" ")[2];
            }
        }
            
        /*System.out.println("\n\n\n\n\n");
        for(String a: part)
            System.out.println(a);*/
        //IDSNN_1_Data.DBConnect db = new IDSNN_1_Data.DBConnect(pass,user,url, tsPath);
        int _fs=0, _fsp=0, _fr=0, _ff=0;
        int _cod=-1;
        int _codP=-1;
        int _codF=-1;
        if(part[6].contains("S.") || (part[5].contains("S.") && !part[5].contains(":"))){
            //System.out.println("Estou em S.");
            String _pAux= part[2];
            part[2]=part[4];
            part[4]=_pAux;
            _fsp=1;
        } else
            if(part[6].contains("S") || (part[5].contains("S") && !part[5].contains(":")))
            {
                //System.out.println("Estou em S");
                _fs=1;
            }else
                if(part[6].contains("R") || (part[5].contains("R") && !part[5].contains(":")))
                {
                   // System.out.println("Estou em R");
                    _fr=1;
                }else
                    if(part[6].contains("F.")  || (part[5].contains("F.") && !part[5].contains(":")))
                    {
                        //System.out.println("Estou em F.");
                        _ff=1;
                    }
        if( _fs==1 || _fsp==1 || _fr==1 || _ff==1)
        {
            int _lastPointIP1 =part[2].lastIndexOf(".");
            part[2]=part[2].substring(0,_lastPointIP1);
            int _lastPointIP2 =part[4].lastIndexOf(".");
            String _port = part[4].substring(_lastPointIP2+1, part[4].length()).replace(':',' ');
            part[4] = part[4].substring(0, _lastPointIP2);
            _cod=db.checkExistingMain(part[2], part[4]);
            if(_cod!=-1)
            {
                _codP=db.checkExistingPort(_cod, _port);
                if(_codP==-1)
                    db.addMainPort(_cod,_port);
                _codF=db.checkExistingFlags(_cod);
                if(_codF!=-1)
                    db.updateFlag(_cod, _fs, _fr, _fsp, _ff, 0);
                else
                    db.addFlag(_cod, _fs, _fr, _fsp, _ff, 0);
            }
            else{
                db.addMainTable(part[2], part[4]);
                _cod=db.checkExistingMain(part[2], part[4]);
                db.addMainPort(_cod,_port);
                db.addFlag(_cod, _fs, _fr, _fsp, _ff, 0);
            }
            db.addWindow(_cod,window);
            //System.out.println("codigo: "+_cod+" window: "+window);
        }
        }
        catch(Exception ex){
            ex.printStackTrace();
            this.readTcpDump();
        }
        finally{
             
        }
    }
}
